/*
 * version May 28, 2011 Thach created constructor and parse method
 * version June 01, 2011 Harman added parsing of credits to teacher types
 */
package parsers;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;

import user.User;
import user.UserType;
import data.ClassPreference;
import data.TimeSlot;

/**
 * @author Thach
 * @version June 01, 2011
 */
public class UserParser {
	private static final String SEPARATOR = ",";
	private final List<User> myUsers;
	private final List<ClassPreference> myClassList;
	private final List<TimeSlot> myTimeList;
	
	/**
	 * 
	 * @pre theFile is formatted appropriately. 
	 * Specifically each line is of the form:
	 * UserID,Name,UserType,numberofTimePref,timePref1,timePref2,...,
	 * numberofClassPref,classPref1,classPref2,...,
	 * @pre theFile, theClassSet, and theTimeSet != null
	 * @post creates a list of Users
	 * @param theFile
	 * @param theClassSet
	 * @param theTimeSet
	 * @throws FileNotFoundException
	 */
	public UserParser(final File theFile, final Set<ClassPreference> theClassSet,
			final Set<TimeSlot> theTimeSet) throws FileNotFoundException {
		myUsers = new LinkedList<User>();
		//Turn sets into lists to get indexable access
		myClassList = new ArrayList<ClassPreference>(theClassSet);
		myTimeList = new ArrayList<TimeSlot>(theTimeSet);
		parse(theFile);
	}

	/**
	 * @param theFile
	 * @throws FileNotFoundException
	 */
	private void parse(final File theFile) throws FileNotFoundException {
		Scanner scan = new Scanner(theFile);

		while (scan.hasNextLine()) {
			StringTokenizer line = new StringTokenizer(scan.nextLine(), SEPARATOR);			
			final int id = Integer.parseInt(line.nextToken()); //parseInt() Throws NumberFormatException
			final String name = line.nextToken();
			final UserType type = UserType.valueOf(line.nextToken());
			User temp = new User(id, name, type);
			// if the user is already in the list
			if (myUsers.contains(temp)) {
				
				temp = myUsers.get(myUsers.indexOf(temp));
				temp.addUserType(type);

			} else {
				myUsers.add(temp);
			}
			int numberOfTimeSlots = Integer.parseInt(line.nextToken());
			while (numberOfTimeSlots > 0) {
				temp.addTime(myTimeList.get(Integer.parseInt(line.nextToken())), type);
				numberOfTimeSlots--;
			}
			int numberOfClassPreferences = Integer.parseInt(line.nextToken());
			while (numberOfClassPreferences > 0) {
				temp.addClass(myClassList.get(Integer.parseInt(line.nextToken())), type);
				numberOfClassPreferences--;
			}
			if (type.equals(UserType.TEACHER))
			{
				temp.setMyMaxCredits(Integer.parseInt(line.nextToken()));
			}
		}
	}

	public List<User> getUserList() {
		return Collections.unmodifiableList(myUsers);
	}

}
